package server

import (
	"ws-demo-go/internal/message/common"
	"ws-demo-go/internal/message/server"
	"ws-demo-go/pkg/logger"
)

// 这个示例展示了如何创建一个简单的Echo服务，收到什么消息就回复什么消息

type Server struct {
	msgServer *server.Server // 消息层服务端
}

// NewBusinessServer 创建业务层服务端实例
func NewBusinessServer(addr string) *Server {
	bs := &Server{
		msgServer: server.NewMessageServer(addr),
	}
	bs.msgServer.SetHook(bs)

	return bs
}

// Start 启动业务层服务端
func (bs *Server) Start() error {
	return bs.msgServer.Start()
}

// Stop 停止业务层服务端
func (bs *Server) Stop() {
	bs.msgServer.Stop()
}

func (bs *Server) OnConnected(msgConn *server.Connection) {
	logger.Info("Client connected: %s", msgConn.ConnID())

	//// 发送欢迎消息
	//welcomeMsg := common.NewMessage(map[string]string{
	//	"message": "Welcome to the business server!",
	//	"connId":  msgConn.ConnID(),
	//})
	//err := msgConn.SendMessage(welcomeMsg)
	//if err != nil {
	//	logger.Error("send welcome message error: %v", err)
	//	return
	//}
}

func (bs *Server) OnDisconnected(msgConn *server.Connection) {
	logger.Info("Client disconnected: %s", msgConn.ConnID())
}

func (bs *Server) OnMessage(msgConn *server.Connection, msg *common.Message) {
	logger.Info("Received message from %s, messageId: %s", msgConn.ConnID(), msg.MessageID)

	// 示例：Echo服务，收到什么就回复什么
	//echoMsg := common.NewMessage(map[string]interface{}{
	//	"originalMessageId": msg.MessageID,
	//	"payload":           msg.Payload,
	//})
	//err := msgConn.SendMessage(echoMsg)
	//if err != nil {
	//	return
	//}
}
